#!/usr/bin/env python

import optparse
import os
import os.path
import sys

import charmicat

def main():
    op = optparse.OptionParser(usage='%prog [opts] cutset path/to/cuts')

    op.add_option("-c", "--cutset", dest="cutsets", action='append', default=[],
                  help="Write report for cutset NAME (can be used more than once)")
    op.add_option("-o", "--output", dest="output", default="cut_summary.txt", 
                  help="Save summary in FILE", metavar="FILE")
    op.add_option("-r", "--replace", action="append", dest="replace", default=[], nargs=2,
                  help="Replace in cutset cut named CUT1 with cut named CUT2")
    op.add_option("-s", dest="list", action='append', default=[],
                  help="Write a report for cut NAME (can be used more than once)")
    op.add_option("-t", "--title", dest='title', default=None,
                  help="Write TITLE as the title for the summary", metavar="TITLE")

    opts, args = op.parse_args()

    if len(args) < 1:
        sys.stderr.write("Please supply the name of an analysis package.\n")
        sys.stderr.write("See `write_cut_summary.py -h' for more.\n")
        sys.stderr.flush()
        return -1

    analysis_name = args.pop(0)

    try:
        analysis      = __import__(analysis_name)
    except ImportError:
        sys.stderr.write("No module `{0}' found. Please check your $PYTHONPATH.\n".format(analysis_name))
        sys.stderr.write("See `write_cut_summary.py -h' for more.\n")
        sys.stderr.flush()
        return -2
        
    if len(args) == 0:
        sys.stderr.write("Please supply the path to the cut directory structure.\n")
        sys.stderr.write("See `write_cut_summary.py -h' for more.\n")
        sys.stderr.flush()
        return -3

    if not opts.title:
        opts.title = analysis.channel_latex + " cut summary:"

    try:
        cut_list = charmicat.build_cut_list(analysis, opts)
    except optparse.OptionError:
        return -4
                

    max_name_len = max([len(cut.name) for cut in cut_list])
    max_desc_len = max([len(cut.desc) for cut in cut_list])

    if max_desc_len > 70:
        max_desc_len = 70

    fpout = open(opts.output, 'w')

    fpout.write(opts.title + "\n\n")

    hdrstr = "{0:{max_name_len}} {1:{max_desc_len}} {2:>10} {3:>14} {4:>10}\n"
    rowstr = "{0:{max_name_len}} {1:{max_desc_len}} {2:>10} {3:>14} {4:>10.4f}\n"

    fpout.write(hdrstr.format('Cut name', 'Cut description', 'Events in', 'Events passed', '% kept',
                              max_name_len=max_name_len, max_desc_len=max_desc_len, ))
    fpout.write('\n')
    
    for cut in cut_list:    
        print cut.name
        cut_dir = os.path.join(os.getcwd(), cut.name)
        os.chdir(cut_dir)

        report_fname = os.path.join(cut_dir, 'report.txt')
        
        if os.access('report.txt', os.F_OK):
            npass, ntot = charmicat.report.parse(report_fname)
        else:
            npass, ntot = charmicat.report.generate(cut_dir) 
        
        percent = float(npass) / float(ntot)
        
        try: 
            fpout.write(rowstr.format(cut.name, 
                                      cut.desc[:max_desc_len], 
                                      ntot, 
                                      npass, 
                                      percent,
                                      max_name_len=max_name_len, 
                                      max_desc_len=max_desc_len, 
                                      )
                        )
        except AttributeError:
            fpout.write(rowstr.format(cut.name, 
                                      '<none specified>', 
                                      ntot, 
                                      npass, 
                                      percent,
                                      max_name_len=max_name_len, 
                                      max_desc_len=max_desc_len,
                                      )
                        )



if __name__ == "__main__":
    sys.exit(main())
